package com.qf.web.common.utils;
import com.qf.common.base.exception.ServiceException;
import com.qf.common.base.result.ResultCode;
import com.qf.web.common.annotations.CacheParam;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 用于对key的组装
 * @author 谢积威
 */
public class RedisKeyUtils {

    private static final String METHOD_PREFIX = "get";

    /**
     * 生成缓存key
     * @param method    目标方法
     * @param args  方法参数列表
     * @param prefix    key的前缀
     * @return
     */
    public static String getCacheKey(Method method,Object[] args,String prefix) {
        String tag = null;
        String key = null;
        int argIndex;
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        mark:
        for (argIndex = 0; argIndex < parameterAnnotations.length; argIndex++) {
            Annotation[] annotations = parameterAnnotations[argIndex];
            for (int j = 0; j < annotations.length; j++) {
                if (annotations[j] instanceof CacheParam){
                    //如果是这个类型，则说明这个参数为我们需要使用的，获取注解中的值
                    tag = ((CacheParam) annotations[j]).value();
                    break mark;
                }
            }
        }
        Class<?> clazz = args[argIndex].getClass();
        try {
            method = clazz.getMethod(METHOD_PREFIX + tag.substring(0, 1).toUpperCase() + tag.substring(1));
            Object o = method.invoke(args[argIndex]);
            key = prefix+o.toString();
        } catch (Exception e) {
            throw new ServiceException(ResultCode.BUSINESS_UNKNOW_ERROR);
        }
        return key;
    }

}
